/**
 * Created by jimmy on 2017/6/11.
 */

var async = require("async");
var orderService = require('../service/OrderService');
var prodService = require('../service/ProdService');
var userService = require('../service/UserService');
var wxpay = require('../lib/wxpay');
var utils = require('../lib/utils');

exports.preOrder = function (req,res,next) {
    var prodId = req.body.prodId;
    var specId = req.body.specId;
    var prodSum = req.body.prodSum;

    async.waterfall([
        function (callbk) {
            prodService.getProd(prodId,callbk);
        },
        function (res,callbk) {
            var prodprice = res[0].product_discount_price;
            var order = {
                user_id:req.session.openid,
                prod_id:prodId,
                spec_id:specId,
                prod_sum:prodSum,
                prod_price:prodprice,
                status:1,
                create_time:new Date(),
                upd_time:new Date()
            }
            console.log(JSON.stringify(order));
            orderService.insPreOrd(order,callbk);
        }
    ],function (err,result) {
        var restr = null;
        if(result.affectedRows>0){
            restr = {code:0,result:"加入成功"};
        }else {
            restr = {code:1,result:"加入失败"};
        }
        res.status(200).end(JSON.stringify(restr));
    })
}

exports.preshop = function (req,res,next) {
    
    async.waterfall([
        function (callbk) {
            orderService.getOrder(req.session.openid,1,callbk);
        },
        function (rows,callbk) {
            var prodod = [];
            for (var i in rows){
                prodod[i] = rows[i].prod_id;
            }
            if(prodod.length>0) {
                prodService.getProdDetail(prodod, 'spec', function (err, specs) {
                    callbk(err, rows, specs);
                });
            }else {
                callbk(null, null, null);
            }
        },
        function (prods,specs,callbk) {
            for(var i in prods){
                var spec = [];
                for (var j in specs){
                    if(prods[i].prod_id == specs[j].product_id){
                        spec.push({id:specs[j].detail_id,specName:specs[j].value});
                    }
                }
                prods[i]["spec"]=spec;
            }

            callbk(null,prods);
        }
    ],function (err,result) {
        console.log(result);
        res.render("shoppingcart",{title:"购物车",home:"",prod:"",prebuy:"on",my:"",prods:result});
    });

}

exports.delOrd = function (req,res,next) {
    var ordId = req.body.ordId;
    async.series({
        del:function (callbk) {
            orderService.delOrder(ordId,callbk);
        }
    },function (err,result) {
        var restr = "";
        if(err) {
            restr = {code:-1,msg:"删除失败"};
        }else {
            restr = {code:0,msg:"删除成功"};
        }
        res.status(200).end(JSON.stringify(restr));
    })
}

exports.addProdSum = function (req,res,next) {
    var ordId = req.body.ordId;
    var sum = req.body.sum;
    async.series({
        del:function (callbk) {
            orderService.addProdSum(ordId,sum,callbk);
        }
    },function (err,result) {
        var restr = "";
        if(err) {
            restr = {code:-1,msg:"修改失败"};
        }else {
            restr = {code:0,msg:"修改成功"};
        }
        res.status(200).end(JSON.stringify(restr));
    })

}

exports.subOrd = function (req,res,next) {
    var ordIds = req.body.orderIds;
    console.log(ordIds)
    async.series({
        sub:function (callbk) {
            orderService.subOrd(ordIds,callbk);
        }
    },function (err,result) {
        var restr = "";
        if(err) {
            restr = {code:-1,msg:"提交失败"};
        }else {
            restr = {code:0,msg:"提交成功",url:"/order/payOrder"};
        }
        res.status(200).end(JSON.stringify(restr));
    })
}

exports.maddress = function (req,res,next) {
    async.series({
       addrInfo:function (callbk) {
            orderService.getAddr(req.session.openid,callbk);
       }
    },function (err,result) {
        res.render('maddress',{title:"地址管理",addressInfo:result.addrInfo})
    });
}

exports.delAddr = function (req,res,next) {
    var addrId = req.query.addrId;
    async.series({
        addrInfo:function (callbk) {
            orderService.delAddr(addrId,callbk);
        }
    },function (err,result) {
        if(err){
            res.status(200).end(JSON.stringify({code:-1,msg:'删除失败'}));
        }else {
            res.status(200).end(JSON.stringify({code:0,msg:'删除成功'}));
        }
    });
}

exports.addAddr = function (req,res,next) {
    var addrInfo = req.query;
    console.log(addrInfo);
    async.series({
        addrInfo:function (callbk) {
            addrInfo.user_id = req.session.openid;
            orderService.addAddr(addrInfo,callbk);
        }
    },function (err,result) {
        if(err){
            res.status(200).end(JSON.stringify({code:-1,msg:'添加失败'}));
        }else {
            res.status(200).end(JSON.stringify({code:0,msg:'添加成功'}));
        }
    });
}

exports.setAddrDef = function (req,res,next) {
    var addrid = req.query.addrId;
    var userid = req.session.openid;
    async.series({
        setdef:function (callbk) {
            orderService.setdef(addrid,callbk);
        },
        setnodef:function (callbk) {
            orderService.setnodef(addrid,userid,callbk)
        }
    },function (err,result) {
        if(err){
            res.status(200).end(JSON.stringify({code:-1,msg:'修改失败'}));
        }else {
            res.status(200).end(JSON.stringify({code:0,msg:'修改成功'}));
        }
    });
}

exports.payOrder = function (req,res,next) {
    var addrId = req.query.addrId;
    async.series({
        addr:function (callbk) {
            if(addrId != null){
                userService.getUserAddrById(req.session.openid,addrId,callbk);
            }else {
                userService.getUserAddr(req.session.openid,callbk)
            }
        },
        ordInfo:function (callbk) {
            orderService.getOrder(req.session.openid,2,callbk);
        },
        freight:function (callbk) {
            orderService.getOrdSendFee(req.session.openid,callbk);
        }
    },function (err,result) {
        var totalmoney = 0;
        var ords = result.ordInfo;
        for (var i in ords){
            console.log(Number(ords[i].prod_price)+"@@@@@@@@@@@@@@@@@@@@@"+Number(ords[i].prod_sum));
            totalmoney += Number(ords[i].prod_price)*Number(ords[i].prod_sum);
        }
        totalmoney += result.freight[0].sendfee;
        res.render("payorder",{title:"订单确认",addr:result.addr,ordInfo:result.ordInfo,freight:result.freight,totalmoney:totalmoney});
    });
}

exports.payOrd = function (req,res,next) {
    async.waterfall([
        function (callbk) {
            orderService.getOrder(req.session.openid,2,callbk);
        },
        function (rows,callbk) {
            var attch = '';
            var totalmoney = 0;
            var outId = new Date().getTime();
            for (var i in rows){
                attch += rows[i].ord_id+"|";
                totalmoney += Number(rows[i].prod_price)*Number(rows[i].prod_sum);
            }
            callbk(null,{attch:attch,totalmoney:totalmoney,outId:outId});
        },
        function (data,callbk) {
            var sendfee = 0;
            orderService.getOrdSendFee(req.session.openid,function (err,rows) {
                sendfee = rows[0].sendfee;
                callbk(null,{attch:data.attch,totalmoney:data.totalmoney,sendfee:sendfee,outId:data.outId});
            });
        },
        function (data,callbk) {
            console.log(data.attch);
            console.log(data.totalmoney);
            console.log(data.outId);
            console.log(data.sendfee);
            wxpay.genPayJS(req.session.openid,data.outId,data.totalmoney+data.sendfee,data.attch,"货星人-商品",function (err,result) {
                if(err){
                    callbk(err,null);
                }else {
                    callbk(null,result);
                }
            });
            
        }
    ],function (err,result) {
        if(err){
            res.status(200).end(JSON.stringify({code:999,msg:"支付失败"}));
        }else {
            result.code = 0;
            res.status(200).end(JSON.stringify(result));
        }
    });
    // wxpay.genPayJS()
}

exports.paynotify = function (req,res,next) {
    async.waterfall([
        function (callbk) {
            var xmlObj = wxpay.parserXML(req.body,callbk);
        },
        function (xmlObj,callbk) {
            var wxRes = xmlObj ? xmlObj['xml'] : null;
            console.log(wxRes);
            if (!wxRes || (wxRes['return_code'] != 'SUCCESS' && wxRes['result_code'] != 'SUCCESS')) {
                callbk("解析失败",null);
            }else {
                var param = {
                    appid: wxRes['appid'],
                    attach: wxRes['attach'],
                    bank_type: wxRes['bank_type'],
                    cash_fee: wxRes['cash_fee'],
                    fee_type: wxRes['fee_type'],
                    is_subscribe: wxRes['is_subscribe'],
                    mch_id: wxRes['mch_id'],
                    nonce_str: wxRes['nonce_str'],
                    openid: wxRes['openid'],
                    out_trade_no: wxRes['out_trade_no'],
                    result_code: wxRes['result_code'],
                    return_code: wxRes['return_code'],
                    sign: wxRes['sign'],
                    time_end: wxRes['time_end'],
                    total_fee: wxRes['total_fee'],
                    trade_type: wxRes['trade_type'],
                    transaction_id: wxRes['transaction_id']
                }
                console.log(JSON.stringify(param));
                orderService.insWxNotify(param,function (err,result) {
                    callbk(err,param);
                });
            }
        },
        function (data,callbk) {
            var attch = data.attach.toString();
            var str = attch.replace('[','').replace(']','');
            console.log(str);
            var ordIds = str.split('|');
            orderService.paySucOrd(ordIds.join(',').substr(0,ordIds.join(',').length-1),callbk)
        }
    ],function (err,result) {
        var restr = '';
        if(err){
            restr = wxpay.getResXml('FAIL',err);
        }else {
            restr = wxpay.getResXml('SUCCESS','ok');
        }
        console.log(JSON.stringify(result));
        res.status(200).end(restr);
    })
}

exports.paySuccess = function (req,res,next) {
    var str = req.query.str;
    var addrId = req.query.addrId;
    async.series({
        prodInfo:function (callbk) {
            prodService.getMainProd(callbk);
        },
        ordInfo:function (callbk) {
            orderService.getPayMoney(str,req.session.openid,callbk);
        },
        addrInfo:function (callbk) {
            userService.getUserAddrById(req.session.openid,addrId,callbk);
        }
    },function (err,result) {
        console.log(result);
        if(!err) {
            orderService.insOrdAddr(result.ordInfo.out_trade_no,addrId,function (err,result) {
                
            });
            res.render("paysuccess", {title: "购买成功", prods: result.prodInfo, ordInfo: result.ordInfo,addrInfo:result.addrInfo});
        }
    });
}

exports.payError = function (req,res,next) {
    var addrId = req.query.addrId;
    var totalfee = req.query.totalfee;
    async.series({
        addrInfo:function (callbk) {
            userService.getUserAddrById(req.session.openid,addrId,callbk);
        }
    },function (err,result) {
        res.render("payerror", {title: "购买失败", addrInfo:result.addrInfo,totalfee:totalfee});
    });
}

exports.updOrdState = function (req,res,next) {
    var ordId = req.query.ordId;
    var status = req.query.status;
    async.series({
        ordSt:function (callbk) {
            if(status == 9){
                orderService.delOrder(ordId,callbk);
            }else if(status == 1){
                orderService.cancelOrd(ordId,callbk)
            }
        }
    },function (err,result) {
        res.status(200).end(JSON.stringify({code:0,msg:'操作成功!'}));
    });
}